class TreeNode {
  val: number
  left: TreeNode | null
  right: TreeNode | null
  constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
    this.val = val === undefined ? 0 : val
    this.left = left === undefined ? null : left
    this.right = right === undefined ? null : right
  }
}

function sumNumbers(root: TreeNode | null, sum = 0): number {
  if (!root) return 0
  const nextSum = sum * 10 + root.val
  if (root.right || root.left) {
    return sumNumbers(root.right, nextSum) + sumNumbers(root.left, nextSum)
  }
  return nextSum
}

export { sumNumbers, TreeNode }
